<template>
  <div class="relative w-full h-full">
    <PageHeader :title="$t('user.权限管理')" />
    <div class="flex_aic_jcsb">
      <el-input
        v-model="queryParams.blurry"
        :placeholder="$t('user.请输入账号')"
        style="width: 256px"
      >
        <template #prefix>
          <span class="color-555555">{{ $t("user.账号") }}</span>
        </template>
      </el-input>
      <div class="flex_aic">
        <el-button @click="resetQuery">{{ $t("user.重置") }}</el-button>
        <el-button type="primary" @click="getList">{{
          $t("user.查询")
        }}</el-button>
      </div>
    </div>
    <div class="mt12 toolbar flex_aic_jcsb" v-my-point="'user:add'">
      <div
        class="addBtn flex_aic_jcc"
        @click="(editDiaData = {}), (editDiaVisible = true)"
      >
        <SvgIcon name="iconxinzeng" class="mr8" />
        <span>{{ $t("user.新增管理员") }}</span>
      </div>
    </div>
    <el-table
      :data="tableData"
      style="width: 100%"
      class="cover-table mt12"
      border
      v-loading="loading"
    >
      <el-table-column :label="$t('user.序号')" width="80">
        <template #default="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="username" :label="$t('user.账号')" />
      <el-table-column :label="$t('user.所属权限组')">
        <template #default="scope">
          <span>{{ getRoleNames(scope.row.roles) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="phone" :label="$t('user.电话')" />
      <el-table-column prop="createTime" :label="$t('user.创建时间')" />
      <el-table-column prop="enabled" :label="$t('user.状态')">
        <template #default="scope">
          <span>{{
            scope.row.enabled ? $t("user.启用") : $t("user.冻结")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('user.操作')" width="380">
        <template #default="scope">
          <div class="operationBtnRow">
            <el-button
              type="text"
              size="small"
              @click="handleEdit(scope.row)"
              v-my-point="'user:edit'"
              >{{ $t("user.编辑") }}</el-button
            >
            <el-button
              type="text"
              size="small"
              @click="handleStatus(scope.row)"
              v-my-point="'user:edit'"
              >{{
                scope.row.enabled ? $t("user.冻结") : $t("user.启用")
              }}</el-button
            >
            <el-button
              type="text"
              size="small"
              @click="handleResetPassword(scope.row)"
              v-my-point="'user:updatePass'"
              >{{ $t("user.重置密码") }}</el-button
            >
            <el-popconfirm
              :title="$t('user.确定删除吗')"
              @confirm="handleDelete(scope.row)"
              :confirm-button-text="$t('user.确定')"
              :cancel-button-text="$t('user.取消')"
              width="300px"
            >
              <template #reference>
                <el-button
                  class="ml0"
                  type="text"
                  size="small"
                  v-my-point="'user:del'"
                  >{{ $t("user.删除") }}</el-button
                >
              </template>
            </el-popconfirm>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <div class="flex justify-end mt24 absolute bottom-0 right-0">
      <el-pagination
        v-model:current-page="queryParams.page"
        v-model:page-size="queryParams.size"
        :page-sizes="[10, 20, 30, 40]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <EditDia
      v-model="editDiaVisible"
      :data="editDiaData"
      @success="submitCallback"
    ></EditDia>
    <ResetPswDia
      v-model="resetPswDiaVisible"
      :data="resetPswData"
      @success="submitCallback"
    ></ResetPswDia>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import EditDia from "./editDia.vue";
import ResetPswDia from "./resetPswDia.vue";
import Api from "@/config/api/api";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import { useI18n } from "vue-i18n";

const { t, locale } = useI18n();
const router = useRouter();
// 查询参数
const queryParams = ref({
  blurry: "",
  page: 1,
  size: 10,
});
const loading = ref(false);
const total = ref(0);
const tableData = ref([]);
const editDiaVisible = ref(false);
const editDiaData = ref({});
const resetPswDiaVisible = ref(false);
const resetPswData = ref({});

// 获取用户列表
const getList = async () => {
  loading.value = true;
  try {
    const res = await Api.users_list({
      ...queryParams.value,
      page: queryParams.value.page - 1,
    });
    if (res.status === 200) {
      tableData.value = res.data.content || [];
      total.value = Number(res.data.totalElements || 0);
    }
  } catch (error) {
    console.error("获取用户列表失败", error);
  } finally {
    loading.value = false;
  }
};

// 重置查询
const resetQuery = () => {
  queryParams.value = {
    blurry: "",
    page: 1,
    size: 10,
  };
  getList();
};

// 删除用户
const handleDelete = async (row) => {
  try {
    await Api.users_delete([row.id]);
    ElMessage.success(t("user.删除成功"));
    getList();
  } catch (error) {
    ElMessage.error(t("user.删除失败"));
    console.error("删除用户失败", error);
  }
};

// 编辑用户
const handleEdit = (row) => {
  editDiaData.value = JSON.parse(JSON.stringify(row));
  editDiaVisible.value = true;
};

// 修改用户状态
const handleStatus = async (row) => {
  try {
    const updateData = {
      ...row,
      enabled: !row.enabled,
    };
    if(updateData.enabled){
      await Api.enable_user(row.id);
    }else{
      await Api.disable_user(row.id);
    }
    ElMessage.success(
      updateData.enabled ? t("user.启用成功") : t("user.冻结成功")
    );
    // if (!updateData.enabled) {
    //   loginOut();
    //   return;
    // }
    getList();
  } catch (error) {
    ElMessage.error(row.enabled ? t("user.冻结失败") : t("user.启用失败"));
  }
};

const loginOut = async () => {
  Api.logout({}).then((res) => {
    if (res.status === 200) {
      Storage.remove("user", true);
      Storage.remove("token", true);
      Storage.remove("menus", true);
      ElMessage.success(t("user.退出成功"));
      router.push("/login");
    }
  });
};

// 重置密码
const handleResetPassword = (row) => {
  resetPswData.value = JSON.parse(JSON.stringify(row));
  resetPswDiaVisible.value = true;
};

// 获取角色名称
const getRoleNames = (roles) => {
  if (!roles || !roles.length) return "-";
  return roles.map((role) => role['name' + locale.value]).join(", ");
};

// 分页大小变更
const handleSizeChange = (size) => {
  queryParams.value.size = size;
  queryParams.value.page = 1;
  getList();
};

// 页码变更
const handleCurrentChange = (page) => {
  queryParams.value.page = page;
  getList();
};

// 提交成功回调
const submitCallback = () => {
  getList();
};

// 页面加载时获取数据
onMounted(() => {
  getList();
});
</script>

<style lang="scss" scoped>
.addBtn {
  height: 28px;
  margin-left: 10px;
  padding: 0 7px;
  border-radius: 3px;
  background: #fff;
  cursor: pointer;
}
.split {
  width: 1px;
  height: 12px;
  background: #ddd;
  margin: 0 5px;
}
</style>
